package com.czk.linkedList.TencetInterview;

import lombok.Data;
import lombok.ToString;

import java.util.Stack;

/**
 * @Author:ChenZhangKun
 * @Date: 2020/6/14 14:19
 */
public class TencentInterviewTest {
    public static void main(String[] args) {
        TencentInterview tencentInterview=new TencentInterview();
        Node node3 = new Node(3);
        Node node2 = new Node(2);
        Node node1 = new Node(1);
        tencentInterview.addNode(node1);
        tencentInterview.addNode(node2);
        tencentInterview.addNode(node3);
        System.out.println(tencentInterview.getReverseNode());
        tencentInterview.printByStack();
    }
}
class TencentInterview{
    Node head=new Node("");
    // 增加元素
    public void addNode(Node node){
        if (head.next==null) {
            head.setNext(node);
            return;
        }
        // 增加
        Node temp=this.head;
        while (true){
            if (temp.next==null){
                temp.setNext(node);
                break;
            }
            temp=temp.next;
        }
    }
    // 翻转链表
    public Node getReverseNode(){
        // 翻转链表的·头结点
        Node node=new Node("");
        if (this.head.next==null||getLength()==0) return null;
        // 链表的长度
        int length = this.getLength();
        if (length==1) return this.head;
        // 遍历原链表
        // 定义辅助变量
        Node current=this.head.next;
        // 下一个节点
        Node next;
        while (current!=null){
            // 当前节点的下一结点
            next=current.next;
            // current的下一结点指向翻转链表的头结点
            // 将翻转列表放在其后面
            current.next=node.next;
            // 将当前节点放在翻转列表前面
            node.next=current;
            // 指针后移
            current=next;
        }
        return node;
    }
    // 获取链表长度
    public int getLength(){
        if (head.next==null) return 0;
        Node temp=head;
        int i=0;
        while (true){
            if (temp.next!=null){
                i++;
            }else {
                break;
            }
            temp=temp.next;
        }
        return i;
    }

    // 利用栈来从最后开始打印
    public void printByStack(){
        Stack<Node> stack=new Stack();
        // 遍历链表，加入栈中
        if (head.next==null) return;
        Node current=head.next;
        while (current!=null){
           stack.add(current);
            current=current.next;
        }
        // 遍历栈
        while (stack.size()>0){
            System.out.println(stack.pop().data);
        }
    }
}
@Data
@ToString
class Node{
    public Object data;
    public Node next;

    public Node(Object data) {
        this.data = data;
    }
}
